<!-- 开发部：裁断完成采集  蹇泽阳 -->
<template>
  <div class="app-container">
    <div v-show="false" id="report" class="print">
      <div v-for="item in printArr" :key="item.lotNo">
        <p style="text-align: center">K.L样品裁断标签</p>
        <div class="List">
          <div class="left">
            <p>{{ item.date }}</p>
            <img :src="item.img" alt="" />
            <p>荣信研发</p>
          </div>
          <div class="right">
            <p>{{ item.lotNo }}</p>
            <p>姓名: {{ item.name }}</p>
            <p>号码: {{ item.number }}</p>
            <p>数量: {{ item.count }}</p>
          </div>
        </div>
      </div>
    </div>

    <Find :OriginalFilter="{ static: true }" :formList="formList" @findClicked="findClicked" />
    <Find :OriginalFilter="{ static: true }" :formList="formList2" :searchImg="false" @findClicked="findClicked2" />
    <div class="mt10" style="width: 100%; background-color: white">
      <el-card shadow="never" :body-style="{ padding: '10px 10px 0' }" class="mt10">
        <div slot="header" class="f16">
          <span style="font-weight: 600" class="mr55">扫描下单条码</span>
        </div>
        <div class="flex mt10 f14" style="align-items: center; justify-content: space-between">
          <div class="">PS:扫描指令单标签时，请确认光标置于此栏位</div>
          <div class="">
            <span class="mr10">扫描条码</span>
            <el-input v-model="scanCode" style="width: 414px; height: 25px; font-size: 20px" />
          </div>
          <div>
            <el-radio-group v-model="radio" class="ml-4">
              <el-radio label="正单" size="large">正单</el-radio>
              <el-radio label="补单" size="large">补单</el-radio>
            </el-radio-group>
          </div>
          <div>
            <span class="mr10">扫描信息</span>
            <el-input disabled v-model="scanMes" style="width: 200px; height: 25px" />
          </div>
        </div>
      </el-card>
      <el-card shadow="never" :body-style="{ padding: '5px 10px 5px' }">
        <h1 class="f16">裁断完成采集</h1>
        <Table
          :isLoading="isLoading"
          :tableHeader="tableHeader"
          :tableData="tableData"
          selection
          class="mt10"
          :outTableHeight="160"
          :summaryData="summaryData"
          summary
          @selectList="selectTable4List"
          @confirmChange="confirmChange"
        />
      </el-card>
      <el-card shadow="never" :body-style="{ padding: '0px 5px 5px' }">
        <PageModule :PageData="{ total: total, buttonS: true }" @pageSizeChange="handleSizeChange" @pageChange="handleCurrentChange" />
      </el-card>
    </div>
  </div>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue'
import { ElMessage } from 'element-plus'
import service from '@/utils/request'
import { debounce } from 'lodash'
import { onMounted, watch } from 'vue'
import LoginWork from '@/utils/LoginWork'
import type { formListType } from '@/components/Find/index.vue'
import { AcquisitionModel, selectList } from '@/plugins/mixin'
import qrcode from 'qrcode'

import JMessage from '@/utils/JMessage'
export default defineComponent({
  name: 'AdjudicationCompleted'
})
</script>
<script lang="ts" setup>
import { i18n, Jzhcn } from '@/i18n'
const scanCode = ref('')
const scanMes = ref('')
const user = ref({
  id: '',
  name: ''
})
watch(
  scanCode,
  debounce(async (val) => {
    if (!scanCode.value) return
    if (scanCode.value.includes('-')) {
      let res = {} as any
      if (radio.value === '正单') {
        res = (await LoginWork.post(`/pack/scanCollectAll?choose=${3}`, {
          lotNo: scanCode.value.toUpperCase(),
          prodType: radio.value,
          workId: user.value.id,
          workName: user.value.name
        })) as any
      } else if (radio.value === '补单') {
        if (!formList2.value[0].selectValue) {
          JMessage.error('请选择责任部门(厂商)')
          return
        }
        if (!formList2.value[1].inputValue) {
          JMessage.error('请输入补单原因')
          return
        }
        if (!formList2.value[2].inputValue) {
          JMessage.error('请输入补单数量')
          return
        }
        res = (await LoginWork.post(`/pack/scanCollectAll?choose=${3}`, {
          lotNo: scanCode.value.toUpperCase(),
          prodType: radio.value,
          workId: user.value.id,
          workName: user.value.name,
          dutyDept: formList2.value[0].selectValue,
          dutyReason: formList2.value[1].inputValue,
          replenishmentQty: formList2.value[2].inputValue
        })) as any
      }

      if (res.code === 200) {
        JMessage.success('扫描成功')
        scanMes.value = scanCode.value
        scanCode.value = ''
        getTableList()
      } else {
        JMessage.error(res.message)
      }
    } else {
      let res = await LoginWork.get<any, any>(`/sdUser/stitch/workName?workId=${scanCode.value}`)
      if (res.code === 200) {
        user.value.id = res.data.workerId
        user.value.name = res.data.workerName
        scanMes.value = res.data.workerName
        scanCode.value = ''
      } else {
        JMessage.error(res.message)
      }
    }
  }, 500)
)
const imgList = ref([])
const radio = ref('正单')
const formList = ref([
  {
    type: 'input',
    inputPlaceholder: '请输入指令号',
    inputValue: ''
  },
  {
    type: 'select',
    selectP: '品牌',
    selectValue: '',
    selectLabel: '',
    selectOptions: []
  },
  {
    type: 'input',
    inputPlaceholder: '请输入货号',
    inputValue: ''
  },
  {
    type: 'date',
    dateLabel: '客户交期',
    dateValue: ''
  },
  {
    type: 'select',
    selectP: '生产员工',
    selectValue: '',
    selectLabel: '',
    selectOptions: []
  },
  {
    type: 'select',
    selectP: '采集员',
    selectValue: '',
    selectLabel: '',
    selectOptions: []
  },
  {
    type: 'date',
    dateLabel: '完成日期',
    dateValue: ''
  },
  {
    type: 'checkbox',
    checkboxLabel: '正单',
    checked: true
  },
  {
    type: 'checkbox',
    checkboxLabel: '补单',
    checked: true
  },
  {
    type: 'button',
    checkboxLabel: '置空'
  },
  {
    type: 'button',
    checkboxLabel: '删除扫描记录'
  },
  {
    type: 'button',
    checkboxLabel: '查询所有采集信息'
  }
])
const formList2 = ref([
  {
    type: 'select',
    selectP: '厂商',
    selectValue: '',
    selectLabel: '',
    selectOptions: []
  },
  {
    type: 'input',
    inputPlaceholder: '请输入补单原因',
    inputValue: ''
  },
  {
    type: 'input',
    inputPlaceholder: '请输入补单数量',
    inputValue: ''
  },
  {
    type: 'button',
    checkboxLabel: '打印派工标签'
  }
])
const tableHeader = ref([
  {
    label: '采集类型',
    prop: 'prodType'
  },
  {
    width: 170,
    label: '指令号',
    prop: 'lotNo'
  },
  {
    label: '品牌',
    prop: 'brand'
  },
  {
    label: '货号',
    prop: 'style'
  },
  {
    label: '颜色',
    prop: 'color'
  },
  {
    label: '号码',
    prop: 'sizeNo',
    width: 50
  },
  {
    label: '订单数量',
    prop: 'orderQty'
  },
  {
    label: '客户交期',
    prop: 'deliveryDate'
  },
  {
    label: '生产员工',
    prop: 'workerName'
  },
  {
    label: '生产数量',
    prop: 'prodQty'
  },
  {
    label: '采集员',
    prop: 'prodUserName'
  },
  {
    label: '责任单位',
    prop: 'dutyDept'
  },
  {
    label: '补单原因',
    prop: 'dutyReason'
  },
  {
    label: '扫描时间',
    prop: 'prodDate'
  },
  {
    type: 'img',
    label: '图片',
    prop: 'photoPath',
    srcList: imgList
  }
])
tableHeader.value.forEach((item: any) => {
  if (item.label === '生产数量' || item.label === '派工数量') {
    item.change = false
  } else {
    item.change = 'Y'
  }
})
// 表一模块
const findClicked = async (content: string) => {
  if (content === '置空') {
    formList.value.forEach((item: any) => {
      item.inputValue = ''
      item.selectValue = ''
      item.dateValue = ''
    })
  }
  if (content === '删除扫描记录') {
    if (selectTableLists.value.length === 0) {
      JMessage.warning('请选择要删除的记录')
      return
    }
    const res = await LoginWork.post<any, any>(`/pack/collect/deleteCollectAll?choose=${3}`, selectTableLists.value)
    if (res.code === 200) {
      JMessage.success('删除成功')
      getTableList()
    } else {
      JMessage.error(res.message)
    }
  }
  if (content === '查询所有采集信息') {
    getTableList(2)
  }
}
const printArr = ref([]) as any
const findClicked2 = async (content: string) => {
  if (content === '打印派工标签') {
    const printHTML = (document.querySelector('#report') as any).innerHTML
    window.document.body.innerHTML = printHTML
    window.print() // 调用浏览器的打印功能打印指定区域
    window.location.reload() // 打印完成后重新加载页面
  }
}

// 表格计算函数
const cfmFlag = () => {
  const Unaudited = formList.value.find((item: any) => item.type === 'checkbox' && i18n.global.t(item.checkboxLabel) === '正单')
  const Audited = formList.value.find((item: any) => item.type === 'checkbox' && i18n.global.t(item.checkboxLabel) === '补单')
  if (!Unaudited || !Audited) return
  if (Unaudited.checked && Audited.checked) {
    return ''
  } else if (Unaudited.checked) {
    return '正单'
  } else if (Audited.checked) {
    return '补单'
  } else {
    ElMessage('必须至少选择一项')
    Unaudited.checked = true
    Audited.checked = true
    return ''
  }
}
const tableData = ref([])
const isLoading = ref(true)
// 总计
interface summaryDataType {
  index: number
  num: number | undefined
}
const summaryData = ref<summaryDataType[]>([
  {
    index: 10,
    num: 0
  }
])
// 分页器
const currentPage = ref(1)
// 定义每页显示数量
const pageSize = ref(40)
// 定义总数量
const total = ref(0)
// 定义每页显示数量改变事件
const handleSizeChange = (val: number) => {
  // 将参数赋值给pageSize
  pageSize.value = val
  // 调用获取表格列表函数
  getTableList()
}
// 定义当前页改变事件
const handleCurrentChange = (val: number) => {
  // 将参数赋值给currentPage
  currentPage.value = val
  // 调用获取表格列表函数
  getTableList()
}

// 获取表数据
const getTableList = debounce(async (type = 1) => {
  // 设置加载状态为true
  isLoading.value = true
  // 调用接口获取数据
  let tableDataList = await service.post<any, any>(`/pack/collect/collectAllList?flag=${type}`, {
    // 选择类型
    choose: '3',
    // 完成日期结束时间
    completeEndTime: formList.value.find(
      (item: any) => item.dateLabel && Jzhcn.Find[item.dateLabel.split('.')[1] as keyof typeof Jzhcn.Find] === '完成日期'
    )?.dateValue?.[1],
    // 完成日期开始时间
    completeStartTime: formList.value.find(
      (item: any) => item.dateLabel && Jzhcn.Find[item.dateLabel.split('.')[1] as keyof typeof Jzhcn.Find] === '完成日期'
    )?.dateValue?.[0],
    // 客户交期结束时间
    deliveryEndTime: formList.value.find(
      (item: any) => item.dateLabel && Jzhcn.Find[item.dateLabel.split('.')[1] as keyof typeof Jzhcn.Find] === '客户交期'
    )?.dateValue?.[1],
    // 客户交期开始时间
    deliveryStartTime: formList.value.find(
      (item: any) => item.dateLabel && Jzhcn.Find[item.dateLabel.split('.')[1] as keyof typeof Jzhcn.Find] === '客户交期'
    )?.dateValue?.[0],
    // 指令号
    lotNo: formList.value.find(
      (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '请输入指令号'
    )?.inputValue,
    // 采集类型 1:正单 2：补单 含有 试板/大货的传入试板/大货
    prodStep: cfmFlag(),
    // 采集员
    prodUserName: formList.value.find((item: any) => item.selectP && Jzhcn.Find[item.selectP.split('.')[1] as keyof typeof Jzhcn.Find] === '采集员')
      ?.selectValue,
    // 货号
    style: formList.value.find(
      (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '请输入货号'
    )?.inputValue,
    // 生产员工
    workerUser: '',
    // 品牌
    brand: formList.value.find((item: any) => item.selectP && Jzhcn.Find[item.selectP.split('.')[1] as keyof typeof Jzhcn.Find] === '品牌')
      ?.selectValue,
    // 当前页码
    pageNum: currentPage.value,
    // 每页数量
    pageSize: pageSize.value
  })
  // 设置加载状态为false
  isLoading.value = false
  // 设置图片列表
  imgList.value = tableDataList.list.map((item: any) => {
    return item.photoPath
  })

  // 设置表格数据
  tableData.value = tableDataList.list.map((item: any) => {
    // 设置交期日期
    item.deliveryDate = item.deliveryDate.split(' ')[0]
    item.change = true
    return item
  })
  // 设置总数量
  total.value = tableDataList.total
  // 设置汇总数据
  summaryData.value[0].num = tableDataList.prodTotal
}, 500)
// 挂载时调用
onMounted(() => {
  getTableList()
})
// 监听表单数据变化时调用
watch(
  () =>
    formList.value.map((item: any) => {
      item.selectValue, item.inputValue, item.dateValue, item.checked
    }),
  () => {
    getTableList()
  }
)

const getSelectList = async () => {
  await selectList(formList, () => service.get('/pcOrder/getPcOrderDataRsjCondition'))
  await selectList(formList, () => service.get('/yield/getCutYieldCondition'))
  await selectList(formList2, () => service.get('/yield/getCutYieldCondition'))
  AcquisitionModel(3, formList)
}
// 当组件挂载完成时，调用getSelectList函数
onMounted(() => {
  getSelectList()
})

const selectTableLists = ref([])
// 定义一个函数，用于接收一个参数selectedList，并将参数selectedList的值赋值给selectTable4Lists的值
const selectTable4List = (selectedList: any) => {
  selectTableLists.value = selectedList
  printArr.value = selectTableLists.value.map((item: any) => {
    let qrCodeData = item.lotNo
    qrcode.toDataURL(qrCodeData, (err: any, url: any) => {
      if (err) {
        JMessage.error(err)
      } else {
        qrCodeData = url
      }
    })
    return {
      img: qrCodeData,
      date: item.prodDate.split(' ')[0],
      lotNo: item.lotNo,
      name: item.workerName,
      number: item.sizeNo,
      count: item.orderQty
    }
  })
}

const confirmChange = async (row: any) => {
  const res = (await LoginWork.post('/pack/updatePcOrderStatus', row)) as any
  if (res.code === 200) {
    JMessage.success('修改成功')
  } else {
    JMessage.error(res.message)
    getTableList()
  }
}
</script>

<style media="print">
.List {
  font-size: 13px;
  margin-top: 1mm;
  display: flex;
  justify-content: space-evenly;
}

.left {
  display: flex;
  flex-direction: column;
  justify-content: space-evenly;
  align-items: center;
}

.right {
  display: flex;
  flex-direction: column;
  justify-content: space-evenly;
  align-items: start;
}

img {
  width: 80px;
  height: 80px;
}
</style>
<style type="text/css" media="print">
@media print {
  html,
  body {
    margin: 0;
    padding: 0;
    width: 60mm;
    height: 40mm;
  }

  @page {
    margin: 1mm;
    size: landscape;
  }
}
</style>
